//
//  SetView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2024/12/26.
//

import SwiftUI
import Kingfisher
import PhotosUI

struct BuyAiCountView2: View {
    @StateObject var viewModel = BuyAiCountViewModel2()
    @StateObject private var paymentManager = PaymentManager()
    
    var body: some View {
        ZStack{
            if !viewModel.status.isEmpty {
                HomeEmptyView(text1: viewModel.status)
                    .frame(maxWidth: .infinity,maxHeight: .infinity)
            } else {
                VStack{
                    ScrollView {
                        //需要嵌套一层LazyVStack，不然会产生间距，而且大小还会随机
                        LazyVStack(alignment: .leading, spacing: 10) {
                            Spacer(minLength: 10)
                            ForEach(Array(viewModel.items.enumerated()), id: \.element.objectId) { index, item in
                                BuyAiCountItemView2(bean: item,isSelected: viewModel.selectedIndex == index)
                                    .contentShape(Rectangle())
                                    .onTapGesture {
                                        viewModel.selectedIndex = index
                                    }
                            }
                            LoadMoreFooter(refreshing: $viewModel.footerRefreshing, action: {
                                viewModel.getData(false)
                            }) {
                                //                            LoadMoreView(noMore: viewModel.noMore, footerRefreshing: viewModel.footerRefreshing)
                            }
                            .noMore(viewModel.noMore)
                            .preload(offset: 10)
                        }
                    }
                    .enableRefresh()
                    .scrollIndicators(.hidden)
                    //底部
                    if isEnable() {
                        HStack {
                            VStack(alignment:.leading, spacing: 0) {
                                HStack(alignment:.bottom,spacing: 0) {
                                    Text("总计：")
                                        .foregroundStyle(.bgItemContent)
                                        .font(.system(size: 16))
                                        .padding(.vertical,4)
                                        .bold()
                                    Text("¥")
                                        .font(.system(size: 14))
                                        .foregroundStyle(.bgItemContent)
                                        .padding(.vertical,4)
                                        .bold()
                                    Text(getPice())
                                        .font(.system(size: 28))
                                        .foregroundStyle(.bgItemContent)
                                        .bold()
                                    Text(".")
                                        .font(.system(size: 14))
                                        .foregroundStyle(.bgItemContent)
                                        .padding(.vertical,4)
                                        .bold()
                                    Text(getPice2())
                                        .font(.system(size: 14))
                                        .foregroundStyle(.bgItemContent)
                                        .padding(.vertical,4)
                                        .bold()
                                }
                                Text("购买越多越划算 ")
                                    .font(.system(size: 10))
                                    .foregroundStyle(.bgDel)
                            }
                            Spacer()
                            Button(action: {
                                if !userManager.isLogin() {
                                    showLoginPopup()
                                    return
                                }
                                showLoadPopup()
                                //执行购买
                                paymentManager.purchaseProduct(withIdentifier: viewModel.getProductId()) { result in
                                    // 处理回调结果
                                    switch result {
                                    case .purchasing:
                                        showToast("正在购买...")
                                    case .purchased:
                                        showLog("购买成功")
                                        viewModel.doBuy(productID: viewModel.getProductId(), bean: viewModel.getBean())
                                    case .failed(let errorMessage):
                                        hideLoadPopup()
                                        showLog("购买失败: \(errorMessage)")
                                    case .restored(let productID):
                                        showLog("恢复购买成功，产品 ID: \(productID)")
                                    case .deferred:
                                        showLog("购买延迟处理")
                                    case .invalidProductID:
                                        hideLoadPopup()
                                        showLog("未找到有效的产品 ID")
                                        showToast("未找到有效的产品 ID")
                                    case .unknown:
                                        hideLoadPopup()
                                        showLog("未知交易状态")
                                    }
                                }
                            }) {
                                Text(getPayStr())
                                    .foregroundColor(.white)
                                    .font(.system(size: 16))
                                    .padding(.horizontal,20)
                                    .padding(.vertical,15)
                                
                            }.background(themeManager.themeColor)
                                .cornerRadius(30)
                        }.padding(.horizontal, 10)
                            .frame(height: 80)
                            .background(.bgItem)
                    }
                }
            }
        }.onAppear{
            if !viewModel.isInit {
                viewModel.getData(true)
                viewModel.isInit = true
            }
        }
    }
    
    func getPice() -> String {
        if viewModel.items.isEmpty {
            return "0"
        }
        let bean = viewModel.getBean()
        let parts = String(bean.price ?? 0.0).components(separatedBy: ".")
        if parts.count == 2 {
            let integerPart = parts[0]  // "3"
            return integerPart
        }
        return bean.price?.stringValue ?? "0"
        
    }
    
    func getPice2() -> String {
        if viewModel.items.isEmpty {
            return "0"
        }
        let bean = viewModel.getBean()
        let parts = String(bean.price ?? 0.0).components(separatedBy: ".")
        if parts.count == 2 {
            let fractionalPart = parts[1] // "14"
            return fractionalPart
        }
        return bean.price?.stringValue ?? "0"
        
    }
    
    func getPayStr() -> String {
        if viewModel.items.isEmpty {
            return "领取"
        }
        let bean = viewModel.items[viewModel.selectedIndex]
        if bean.price ?? 0.0 <= 0.0 {
            return "领取"
        }
        return "确认支付"
        
    }
    
    func isEnable()-> Bool {
        if viewModel.items.isEmpty {
            return false
        }
        let bean = viewModel.getBean()
        return bean.enabled()
        
    }
}

//#Preview {
//    SetView()
//}


//定义预览提供者
struct BuyAiCountView2_Previews: PreviewProvider {
    static var previews: some View {
        //使用预览共享配置
        configurePreviewEnvironment(for: BuyAiCountView2())
    }
}
